import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
import inquirer from 'inquirer';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const projectsPath = path.join(__dirname, '..', 'projects');

async function createProject() {
    const { projectName, port } = await inquirer.prompt([
        {
            type: 'input',
            name: 'projectName',
            message: '请输入新项目名称：',
            validate: input => {
                if (!input) return '项目名称不能为空';
                if (fs.existsSync(path.join(projectsPath, input))) {
                    return '项目已存在，请使用其他名称';
                }
                return true;
            }
        },
        {
            type: 'input',
            name: 'port',
            message: '请输入开发环境端口号：',
            default: '2801',
            validate: input => {
                const port = parseInt(input);
                if (isNaN(port) || port < 1 || port > 65535) {
                    return '请输入有效的端口号（1-65535）';
                }
                return true;
            }
        }
    ]);

    const templatePath = path.join(projectsPath, 'template');
    const newProjectPath = path.join(projectsPath, projectName);

    try {
        // 使用自定义复制选项
        await fs.copy(templatePath, newProjectPath, {
            filter: (src) => {
                // 排除 node_modules 目录
                return !src.includes('node_modules');
            },
            dereference: true  // 解析符号链接
        });

        // 更新新项目的 package.json
        const packageJsonPath = path.join(newProjectPath, 'package.json');
        if (fs.existsSync(packageJsonPath)) {
            const packageJson = await fs.readJson(packageJsonPath);
            packageJson.name = projectName;
            await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });
        }

        // 更新 .env 文件
        const envPath = path.join(newProjectPath, '.env');
        if (fs.existsSync(envPath)) {
            let envContent = await fs.readFile(envPath, 'utf8');
            envContent = envContent.replace(/VUE_APP_PREFIX\s*=\s*.*/, `VUE_APP_PREFIX = ${projectName}`);
            await fs.writeFile(envPath, envContent, 'utf8');
        }

        // 更新 .env.development 文件
        const envDevPath = path.join(newProjectPath, '.env.development');
        if (fs.existsSync(envDevPath)) {
            let envDevContent = await fs.readFile(envDevPath, 'utf8');
            envDevContent = envDevContent.replace(/VUE_APP_PORT\s*=\s*\d+/, `VUE_APP_PORT = ${port}`);
            await fs.writeFile(envDevPath, envDevContent, 'utf8');
        }

        console.log(`✨ 项目 ${projectName} 创建成功！`);
        console.log(`👉 请执行 install-all 安装依赖`);
    } catch (error) {
        console.error('创建项目失败：', error);
    }
}

createProject();